import React, { useState, useEffect, useRef } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Button, Divider, Form, Input, message, Modal, Popconfirm, Space, Upload } from 'antd';
import { connect, FormattedMessage, useIntl } from 'umi';
import type { ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import request from '@/utils/request';
import CateComp from '@/components/CategoryComponent';
import UploadUtil from '@/components/UploadUtil';

const apiURL = '/api/services/app/LangConfig/';
const currentControl = 'LangConfig';

const ViewLangConfig: React.FC<any> = (props) => {
  const [loading, setLoading] = useState(false);
  const [visible, setVisible] = useState(false);
  const [dataSource, setDataSource] = useState([]);
  const [locales, setLocales] = useState([]);
  const [pageSize, setPageSize] = useState(10);
  const [params, setParams] = useState<any>({});
  const formRef = useRef<any>();
  const proTbRef = useRef<ActionType>();
  const intl = useIntl();
  useEffect(() => {
    fetchLocale();
  }, []);

  const fetchLocale = () => {
    request('/api/services/app/Category/GetCates', {
      method: 'GET',
      params: { layout: 'locales' },
    }).then((response) => {
      if (response && response.success) {
        const locales = response.result.map((item: any) => ({
          label: item.categoryName,
          value: item.categoryIndex,
        }));
        setLocales(locales);
      }
    });
  };

  const fetchData = async (params: any = null, maxResultCount: any, skipCount: any) => {
    setLoading(true);
    const result: any = { data: [], total: 0 };
    await request(apiURL + 'GetList', {
      method: 'GET',
      params: {
        keywords: params?.keyName,
        lang: params?.locales,
        skipCount,
        maxResultCount,
      },
    }).then((response) => {
      if (response && response.success) {
        result.data = response.result.items;
        result.total = response.result.totalCount;
        setDataSource(response.result.items);
      }
      setLoading(false);
    });
    return result;
  };

  const onFinish = (values: any) => {
    const act = values.id === 0 || !values.id ? 'Abp/create' : 'Abp/update';
    setLoading(true);
    props
      .dispatch({
        type: act,
        payload: values,
        control: currentControl,
      })
      .then(() => {
        const resp = props.response;
        if (resp.result) {
          message.success(intl.formatMessage({id: 'pages.save.success'}));
          proTbRef.current?.reload();
        }
        setLoading(false);
      });
  };

  const doDel = (id: any) => {
    request(apiURL + 'Delete', {
      method: 'DELETE',
      params: { id },
    }).then((response) => {
      if (response && response.success) {
        message.success(intl.formatMessage({id: 'pages.delete.success'}));
        proTbRef.current?.reload();
      }
    });
  };

  const ResetForm = () => {
    formRef.current?.resetFields();
  };

  const handlerExport = async () => {
    const resp = await request('/api/Excel/ExportLanguage', {
      method: 'POST',
      params: {
        keywords: params?.keyName,
        lang: params?.locales,
      },
      responseType: 'blob',
    });
    try {
      const url = window.URL.createObjectURL(resp);
      const a = document.createElement('a');
      a.href = url;
      a.download = 'language.xls';
      a.click();
    } catch (e) {
      console.log(e);
    }
  };

  const handlerImport = (info: any) => {
    setLoading(true);
    if (info.file.status === 'done') {
      message.success(intl.formatMessage({id: 'pages.import.success'}));
      setLoading(false);
    }
  };

  const columns = [
    {
      title: <FormattedMessage id="pages.KeyName" />,
      dataIndex: 'keyName',
      valueType: 'text',
    },
    {
      title: <FormattedMessage id="pages.KeyValue" />,
      dataIndex: 'keyValue',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: <FormattedMessage id="pages.Locales" />,
      dataIndex: 'locales',
      valueType: 'select',
      fieldProps: {
        options: locales,
      },
    },
    {
      title: <FormattedMessage id="pages.operation" />,
      valueType: 'option',
      render: (text: any, record: any, _: any, action: any) => (
        <span>
          <a
            key="editable"
            onClick={() => {
              action?.startEditable?.(record.id);
            }}
          >
            {' '}
            <FormattedMessage id="pages.edit" />{' '}
          </a>
          <Divider type="vertical" />
          <Popconfirm
            title={<FormattedMessage id="pages.confirmDelete" />}
            onConfirm={() => doDel(record.id)}
          >
            <a>
              <FormattedMessage id="pages.delete" />
            </a>
          </Popconfirm>
        </span>
      ),
    },
  ];
  const layout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 18 },
  };
  return (
    <PageHeaderWrapper title={false} breadcrumbRender={false} ghost>
      <ProTable
        tooltip={intl.formatMessage({id: 'pages.lngconfig.tip'})}
        actionRef={proTbRef}
        columns={columns}
        cardBordered
        request={async (params = {}) => {
          const pageIndex = params.current ? params.current : 1;
          const pageNum = params.pageSize ? params.pageSize : 0;
          setParams(params);
          return fetchData(params, params.pageSize, (pageIndex - 1) * pageNum);
        }}
        editable={{
          type: 'multiple',
          actionRender: (row, config, dom) => [dom.save, dom.delete, dom.cancel],
          onSave: async (rowKey, data, row) => {
            onFinish(data);
            console.log(row);
          },
          onDelete: async (rowKey, row) => {
            doDel(rowKey);
            console.log(row);
          },
        }}
        rowKey="id"
        search={{ labelWidth: 'auto' }}
        pagination={{
          pageSize,
          onChange: (page, _pageSize) => setPageSize(_pageSize),
        }}
        headerTitle={<FormattedMessage id="pages.LanguageList" />}
        toolBarRender={() => [
          <Button key="button" type="primary" onClick={() => setVisible(true)}>
            <FormattedMessage id="pages.create" />
          </Button>,
          <Button key="button" type="default" onClick={handlerExport}>
            <FormattedMessage id="pages.export" />
          </Button>,
          <Upload
            accept=".xls,.xlsx,application/vnd.ms-excel"
            name="file"
            action="/api/Excel/ImportLanguage"
            headers={{ Authorization: UploadUtil.accessToken }}
            beforeUpload={UploadUtil.checkExcel}
            showUploadList={false}
            onChange={handlerImport}
          >
            <Button loading={loading}>
              <FormattedMessage id="pages.import" />
            </Button>
          </Upload>,
        ]}
      />
      <Modal
        title={<FormattedMessage id="pages.create" />}
        visible={visible}
        destroyOnClose={true}
        onCancel={() => setVisible(false)}
        footer={false}
        closable
      >
        <Form {...layout} ref={formRef} onFinish={onFinish}>
          <Form.Item hidden label="id" name="id">
            <Input />
          </Form.Item>
          <Form.Item
            name="keyName"
            label={<FormattedMessage id="pages.KeyName" />}
            rules={[{ required: true, message: intl.formatMessage({id: 'pages.KeyName.required'}) }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="keyValue"
            label={<FormattedMessage id="pages.KeyValue" />}
            rules={[{ required: true, message: intl.formatMessage({id: 'pages.KeyValue.required'}) }]}
          >
            <Input />
          </Form.Item>
          <CateComp
            layout="Locales"
            width={200}
            name="locales"
            label={<FormattedMessage id="pages.Locales" />}
            required
            rules={[{ required: true, message: <FormattedMessage id="pages.PleaseEntryLocales" /> }]}
          />
          <Form.Item wrapperCol={{ offset: layout.labelCol.span }}>
            <Space>
              <Button type="primary" htmlType="submit" loading={loading}>
                <span>
                  <FormattedMessage id="pages.save" />
                </span>
              </Button>
              <Button onClick={ResetForm}>
                <span>
                  <FormattedMessage id="pages.reset" />
                </span>
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </PageHeaderWrapper>
  );
};

export default connect(({ Abp }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
}))(ViewLangConfig);
